package com.example.zhyq.login

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import com.alibaba.android.arouter.facade.annotation.Route

import com.alibaba.android.arouter.launcher.ARouter
import com.blankj.utilcode.util.SPUtils
import com.blankj.utilcode.util.ToastUtils
import com.example.base.mvvm.BaseActivity
import com.example.zhyq.R
import com.example.zhyq.databinding.ActivityLoginBinding
import dagger.hilt.android.AndroidEntryPoint

@AndroidEntryPoint
@Route(path = "/app/LoginActivity")
class LoginActivity : BaseActivity<ActivityLoginBinding,UserViewModel>() {


    override fun initView() {

        val token = SPUtils.getInstance().getString("token")
        if (token.isNotEmpty()) {
            ARouter.getInstance().build("/app/MainActivity").navigation()
            finish()
        }

        binding.btnLogin.setOnClickListener {
            val user = binding.etUser.text.toString()
            val pass = binding.etPass.text.toString()

            if (user.isNullOrEmpty() || pass.isNullOrEmpty()) {
                ToastUtils.showLong("输入不能为空")
                return@setOnClickListener
            }

//            if(!user.matches(Regex("[A-z0-9_]{2,8}"))){
//                ToastUtils.showLong("不是合法账号")
//                return@setOnClickListener
//            }
            vm.login(user,pass)
        }

        binding.goRegister.setOnClickListener {
            ARouter.getInstance().build("/app/RegisterActivity").navigation()
            finish()
        }
    }

    override fun initData() {
        vm.loginSuc.observe(this) {
            ToastUtils.showLong("登录成功")
            SPUtils.getInstance().put("token",it.token)
            SPUtils.getInstance().put("username",it.username)
            SPUtils.getInstance().put("uid",it.id)
            ARouter.getInstance().build("/app/MainActivity").navigation()

            if (it.roleid==2){
                ARouter.getInstance().build("/app/MainActivity").navigation()
            }else {
                ARouter.getInstance().build("/app/WebViewActivity").navigation()
            }
            finish()
        }
    }
}